package com.yunze.polling.card;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.yunze.apiCommon.utils.InternalApiRequest;
import com.yunze.apiCommon.utils.VeDate;
import com.yunze.common.core.redis.RedisCache;

import com.yunze.common.utils.yunze.CardFlowSyn;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 卡用量轮询消费 者
 */
@Slf4j
@Component
public class CardFlow {


    @Resource
    private InternalApiRequest internalApiRequest;
    @Resource
    private CardFlowSyn cardFlowSyn;
    /*@Resource
    private TdbPollingMapper tdbPollingMapper;*/




    /**
     *
     * @param msg
     * @param channel_1
     * @throws IOException
     */
    @RabbitHandler
    @RabbitListener(queues = "polling_cardCardFlow_queue",containerFactory = "customContainerFactory")
    public void cardCardFlow_exchange(String msg, Channel channel_1) {
        if(msg!=null && msg.length()>0){
            synCardFlow(msg,true);
        }
    }


    /**
     * 死信队列
     * @param msg
     * @param channel_1
     * @throws IOException
     */
    @RabbitHandler
    @RabbitListener(queues = "polling_dlxcardCardFlow_queue",containerFactory = "customContainerFactory")
    public void dlxcardCardFlow_exchange(String msg, Channel channel_1)  {
        if(msg!=null && msg.length()>0){
            synCardFlow(msg,true);
        }
    }



    /**
     *日用量记录为 负数 卡号 再次同步用量
     * @param msg
     * @param channel_1
     * @throws IOException
     */
    @RabbitHandler
    @RabbitListener(queues = "polling_cardCardFlowLessThanZero_queue",containerFactory = "customContainerFactory")
    public void CardCardFlowLessThanZero(String msg, Channel channel_1) {
        if(msg!=null && msg.length()>0){
            synCardFlow(msg,false);
        }
    }


    /**
     * 用量轮询补偿
     * @param msg
     * @param channel_1
     */
    @RabbitHandler
    @RabbitListener(queues = "polling_FlowCompensate_queue",containerFactory = "customContainerFactory")
    public void PollingFlowCompensate_queue(String msg, Channel channel_1) {
        if(msg!=null && msg.length()>0){
            if (StringUtils.isEmpty(msg)) {
                return;
            }
            synCardFlow(msg,true);
        }
    }


    /**
     * 死信队列
     * @param msg
     * @param channel_1
     * @throws IOException
     */
    @RabbitHandler
    @RabbitListener(queues = "dlx_polling_FlowCompensate_queue",containerFactory = "customContainerFactory")
    public void DlxPollingFlowCompensate_queue(String msg, Channel channel_1)  {
        if(msg!=null && msg.length()>0){
            if (StringUtils.isEmpty(msg)) {
                return;
            }
            synCardFlow(msg,true);
        }
    }




    /**
     * 同步卡用量
     *
     * @param msg
     * @throws IOException
     */
    public void synCardFlow(String msg, boolean is_Record) {
        String polling_id = "";
        String iccid = "";
        String status = "0";
        Map<String, Object> pLogMap = new HashMap<>();

        try {
            if (StringUtils.isEmpty(msg)) {
                return;
            }
            Map<String, Object> map = JSON.parseObject(msg);
            if(is_Record){
                polling_id = map.get("polling_id").toString();//轮询任务编号
            }
            iccid = map.get("iccid").toString();
                Map<String, Object> Parammap = new HashMap<>();
                Parammap.put("iccid", iccid);
                Map<String, Object> Rmap = internalApiRequest.queryFlow(Parammap, map);
                String code = Rmap.get("code") != null ? Rmap.get("code").toString() : "500";
                if (code.equals("200")) {
                    //获取 卡用量 开卡日期 更新 card info
                    if (Rmap.get("Use") != null && Rmap.get("Use") != "" && Rmap.get("Use").toString().trim().length() > 0) {
                        Double Use = Double.parseDouble(Rmap.get("Use").toString());
                        if (Use >= 0) {
                            try {
                                Map<String, Object> RMap = cardFlowSyn.CalculationFlow(iccid, Use);
                                log.info(">>cardFlowSyn - 卡用量轮询消费者 同步卡用量返回:{} | {} | {} | {} <<", polling_id, iccid, JSON.toJSON(RMap), JSON.toJSON(Rmap));
                                boolean bool_info = RMap.get("bool_info")!=null? (boolean) RMap.get("bool_info") :false;
                                if(bool_info){
                                    status = "1";
                                }
                            } catch (Exception e) {
                                log.error(">>cardFlowSyn - 卡用量轮询消费者 同步卡用量失败:{} | {} | {}  | {}<<", polling_id, iccid, JSON.toJSON(Rmap) , e.getMessage().toString());
                            }
                        } else {
                            log.info(">>API - 卡用量轮询消费者 未获取到卡用量 {} |  statusCode = 0 :{} | {}<<", polling_id, iccid, Rmap);
                        }
                    }
                } else {
                    log.info(">>API - 卡用量轮询消费者 未获取到卡用量:{} | {} | {}<<", polling_id, iccid, Rmap);
                }
        } catch (Exception e) {
            log.error(">>错误 - 卡用量轮询消费者:{}<<", e.getMessage());
        }

        if(is_Record){
            if(polling_id!=null && iccid!=null && polling_id.length()>0 && polling_id.length()>0){
                //redisCache.setCacheObject(polling_id + ":" + prefix + ":" + iccid, msg, 1, TimeUnit.HOURS);//1 小时缓存 用来统计轮询进度
                pLogMap.put("ts",VeDate.getStringDateSSS());
                pLogMap.put("polling_id", polling_id);
                pLogMap.put("status",status);
                pLogMap.put("iccid",iccid);
                pLogMap.put("message",msg);

                /*try {
                    tdbPollingMapper.insert(pLogMap);
                }catch (Exception e){
                    log.error("tdbPollingMapper.insert 异常 {} ||  {} ",pLogMap,e.getMessage());
                }*/

            }
        }
    }


}
